import { initEditor, getValue, setValue, setCursorTo, getLineCount, getLineLength } from './editor';
import { parseFile, renderTable } from './data';

document.addEventListener('DOMContentLoaded', () => {
  const app = document.getElementById('app');
  if (app) {
    app.innerHTML = `
      <div class="container">
        <h1>Excel Process Extension - 全屏</h1>
        <div class="input-group">
          <div id="editor" style="height: 360px; width: 100%; border: 1px solid #ccc; border-radius: 8px;"></div>
          <input type="file" id="fileInput" accept=".xlsx,.csv">
        </div>
        <div id="error" class="error"></div>
        <div id="fileContent" class="content"></div>
      </div>
    `;

    const fileInput = document.getElementById('fileInput') as HTMLInputElement;
    const fileContent = document.getElementById('fileContent');
    const errorDiv = document.getElementById('error');
    let lastCommand = '';
    let fileCount = 0;

    // 初始化编辑器
    let editorValue = 'load file';
    initEditor(document.getElementById('editor')!, editorValue, (content) => {
      // 只检测最后一行是否为'load file.'
      const lines = content.split('\n');
      const lastLine = lines[lines.length - 1].trim();
      if (/^load file\.$/i.test(lastLine)) {
        fileInput.value = '';
        fileInput.click();
        lastCommand = lastLine;
      }
    });

    fileInput.addEventListener('change', async () => {
      const file = fileInput.files?.[0];
      if (file) {
        fileCount += 1;
        const dataName = `data${fileCount}`;
        const fullPath = file.name;
        // 替换最后一行
        const lines = getValue().split('\n');
        lines[lines.length - 1] = `${lastCommand.replace(/\.$/, '.')}\`${fullPath}\` as ${dataName};`;
        setValue(lines.join('\n') + '\n');
        // 光标移动到最后一行末尾
        const lineCount = getLineCount();
        const lastLineLength = getLineLength(lineCount);
        setCursorTo(lineCount, lastLineLength + 1);
        // 解析skip N
        const lastLine = lines[lines.length - 1];
        const skipMatch = lastLine.match(/skip\s+(\d+)/i);
        const skipRows = skipMatch ? parseInt(skipMatch[1], 10) : 0;
        try {
          const json = await parseFile(file, skipRows);
          if (errorDiv) errorDiv.textContent = '';
          if (fileContent) fileContent.innerHTML = renderTable(json);
        } catch (error: any) {
          if (errorDiv) errorDiv.textContent = error.message || '解析文件时发生错误，或文件编码不受支持';
          if (fileContent) fileContent.textContent = '';
        }
      }
    });
  }
}); 